import axios from 'axios'
import EventEmitter from './EventEmitter.js'

const server = axios.create({
    baseURL: import.meta.env.VITE_API_URL
})

server.interceptors.request.use(config => {
    return config;
}, error => {
    return Promise.reject(error);
});

server.interceptors.response.use(response => {
    if(response.status === 200){
        if(response.data.code === 400){            
            return EventEmitter.emit('API:UN_AUTH')
        }
        return response.data
    }
    EventEmitter.emit('API_ERROR', response)
}, error => {
    return Promise.reject(error);
});

export const apiGet = (url, params) =>  server({ url, method:'get', params})

export const apiPost = (url, data) =>  server({ url, method:'post', data })

export const apiPut = (url, data) => server({ url, method:'put', data })

export const apiDel = (url, params) => server({ url, method:'delete', params })

export default  server


// export const apiUpload = (url, file, onProgress) => {
//     const formData = new FormData();
//     formData.append('file', file);
    
//     const controller = new AbortController();
    
//     return {
//         promise: server({
//             url,
//             method: 'post',
//             data: formData,
//             signal: controller.signal,
//             headers: {
//                 'Content-Type': 'multipart/form-data'
//             },
//             onUploadProgress: (progressEvent) => {
//                 const percent = Math.floor(
//                     (progressEvent.loaded / progressEvent.total) * 100
//                 );
//                 onProgress?.(percent);
//             }
//         }),
//         abort: () => controller.abort()
//     };
// };